package bme.andraskindler.treenventory.activity;

import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import bme.andraskindler.treenventory.TreenventoryApplication;
import bme.andraskindler.treenventory.R;
import bme.andraskindler.treenventory.fragment.ProgressDialogFragment;
import bme.andraskindler.treenventory.fragment.TreeChooserDialogFragment;
import bme.andraskindler.treenventory.imagemanipulation.Filters;
import bme.andraskindler.treenventory.imagemanipulation.Vector;
import bme.andraskindler.treenventory.model.MeasureResult;
import bme.andraskindler.treenventory.model.TreeData;
import bme.andraskindler.treenventory.provider.TreenventoryDataSource;
import bme.andraskindler.treenventory.widget.ZoomImageView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.model.LatLng;

/**
 * 
 * @author andraskindler
 * 
 *         Ez az activity a törzs szélességének méréséért felel. Emellett megjeleníti az eredményt, valamint a felhasználó itt töltheti ki a fatípust.
 */
public class MeasureActivity extends SherlockFragmentActivity {

	private ImageTask mTask;
	private ZoomImageView mZoomImageView;
	private TextView mDiameter, mType, mCoords;
	private TreeData mCurrent;

	public static final int TYPE_RESULT = 22;

	/**
	 * 
	 * @author andraskindler
	 * 
	 *         Ez a belső osztály egy háttérszálon indítja el a szélesség meghatározását.
	 * 
	 */
	protected class ImageTask extends AsyncTask<Bitmap, Void, MeasureResult> {

		private ProgressDialogFragment mProgressDialogFragment;

		public ImageTask() {
		}

		@Override
		protected MeasureResult doInBackground(Bitmap... params) {
			final LatLng origcoords = getIntent().getParcelableExtra(LatLng.class.getCanonicalName());
			final double angle = getIntent().getExtras().getFloat("angle");

			SharedPreferences preferences = getSharedPreferences(OptionsActivity.SETTINGS, Context.MODE_PRIVATE);
			final MeasureResult measureresult = Filters.measureTrunk(params[0], preferences.getInt(OptionsActivity.SETTINGS_HEIGHT, 25), OptionsActivity.SETTINGS_TRESHOLD, preferences.getInt(OptionsActivity.SETTINGS_ACCURACY, 1), Filters.CAMERA_MAIN);

			final LatLng newcoords = Vector.addCamTreeDistance(measureresult.getTreeDistance(), origcoords, angle);
			mCurrent.setLatitude(newcoords.latitude);
			mCurrent.setLongitude(newcoords.longitude);

			return measureresult;
		}

		@Override
		protected void onPostExecute(MeasureResult result) {
			mProgressDialogFragment.dismiss();
			System.out.println(result.getProcessedImage() == null);
			mZoomImageView.init(result.getProcessedImage());
			mDiameter.setText("Szélesség: " + Double.toString(result.getWidth()));
			mCurrent.setWidth(result.getWidth());
			mCoords.setText("Koordináták: " + mCurrent.getLatitude() + " " + mCurrent.getLongitude());
			mZoomImageView.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPreExecute() {
			mProgressDialogFragment = ProgressDialogFragment.newInstance("Kérem, várjon", "Képfeldolgozás folyamatban");
			mProgressDialogFragment.show(getSupportFragmentManager(), "fragment_progress_dialog");
		}

		protected void onCancelled() {
			super.onCancelled();
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		final View root = getLayoutInflater().inflate(R.layout.activity_measure, null);
		setContentView(root);

		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		mZoomImageView = ZoomImageView.class.cast(root.findViewById(R.id.ziv_measure));

		mTask = new ImageTask();
		final Bitmap bmp = TreenventoryApplication.getCameraImage();
		mTask.execute(bmp);

		mCurrent = new TreeData();
		mCurrent.setDate(System.currentTimeMillis());
		final LatLng coords = getIntent().getParcelableExtra(LatLng.class.getCanonicalName());
		mCurrent.setLatitude(coords.latitude);
		mCurrent.setLongitude(coords.longitude);

		TextView.class.cast(root.findViewById(R.id.tv_measure_date)).setText("Dátum: " + new Date(mCurrent.getDate()).toLocaleString());
		mCoords = TextView.class.cast(root.findViewById(R.id.tv_measure_coords));
		mType = TextView.class.cast(root.findViewById(R.id.tv_measure_type));
		mDiameter = TextView.class.cast(root.findViewById(R.id.tv_measure_diameter));

		mType.setText("Típus: ");

		Button.class.cast(root.findViewById(R.id.btn_measure_type)).setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				TreeChooserDialogFragment.newInstance().show(getSupportFragmentManager(), TreeChooserDialogFragment.class.getCanonicalName());
			}
		});

		Button.class.cast(root.findViewById(R.id.btn_measure_save)).setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				TreenventoryDataSource.persistTree(mCurrent);
				finish();
			}
		});
	}

	@Override
	public void onBackPressed() {
		if (mTask != null && (mTask.getStatus() == AsyncTask.Status.RUNNING || mTask.getStatus() == AsyncTask.Status.PENDING)) {
			mTask.cancel(true);
		}
		super.onBackPressed();
	}

	public void setType(final String string) {
		mType.setText(string);
		mCurrent.setType(string);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			setType(data.getStringExtra("result"));
		} else if (resultCode == RESULT_CANCELED) {
			Toast.makeText(this, "Hiba a típus megadásakor, kérem, próbálja úlra", Toast.LENGTH_SHORT).show();
		}
	}

}
